//
//  UPGridView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/18.
//

// UPGridView.m
#import "UPGridView.h"
#import <Masonry/Masonry.h>

@implementation UPGridView

- (instancetype)initWithItems:(NSArray<UPGridItem *> *)items {
    self = [super init];
    if (self) {
        if (items.count != 4) return self;
        
        // 1. 创建两行容器
        UIView *row1 = [[UIView alloc] init];
        UIView *row2 = [[UIView alloc] init];
        [self addSubview:row1];
        [self addSubview:row2];
        
        // 2. 添加 Items
        [row1 addSubview:items[0]];
        [row1 addSubview:items[1]];
        [row2 addSubview:items[2]];
        [row2 addSubview:items[3]];
        
        // 3. 行约束（关键：不固定高度）
        CGFloat spacing = 15;
        [row1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
        }];
        
        [row2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(row1.mas_bottom).offset(spacing);
            make.left.right.bottom.equalTo(self);
        }];
        
        // 4. Item 约束（等宽等高，间距15）
        [items[0] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(row1);
            make.width.equalTo(row1).multipliedBy(0.5).offset(-spacing/2);
        }];
        
        [items[1] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.equalTo(row1);
            make.width.equalTo(items[0]);
            make.left.equalTo(items[0].mas_right).offset(spacing);
        }];
        
        [items[2] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(row2);
            make.width.equalTo(row2).multipliedBy(0.5).offset(-spacing/2);
        }];
        
        [items[3] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.top.bottom.equalTo(row2);
            make.width.equalTo(items[2]);
            make.left.equalTo(items[2].mas_right).offset(spacing);
        }];
        
        // 5. 强制同步所有 Item 的高度（以第一张图片为基准）
        if (items.count > 0) {
            [items enumerateObjectsUsingBlock:^(UPGridItem *item, NSUInteger idx, BOOL *stop) {
                if (idx > 0) {
                    [item mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.height.equalTo(items[0]);
                    }];
                }
            }];
        }
    }
    return self;
}
@end
